package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.adapter.SupGoodsListAdapter;
import com.aoxon.cargo.bean.Cloth;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.cache.SupCache;
import com.aoxon.cargo.cache.keyCache;
import com.aoxon.cargo.component.MyListBottom;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.GoodsFromSupplierService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.SearchGoodsFormTextAndSupplier;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.DisplayUtil;
import com.aoxon.cargo.util.EnvironmentUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.google.gson.reflect.TypeToken;

/**
 * 供应商商品管理
 * 
 * @author ZZJ
 * 
 */
public class SupGoodsManagerActivity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {

	private int length = 20;
	private int startIndex = 0;
	private int visibleLastIndex;
	private boolean isReachLast = false;

	private ImageView ivReturnButton;
	private ImageView ivAddGoodsButton;

	private EditText etGoodsManagerSearch;

	private TextView tvTitle;

	private ListView lvGoodsManagerList;

	private SupGoodsListAdapter adater;
	private MyListBottom myListBottom;

	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);

	private String strSearchText = new String();
	private List<Cloth> cloths = new ArrayList<Cloth>();

	private SearchGoodsFormTextAndSupplier searchGoodsFormTextAndSupplier = (SearchGoodsFormTextAndSupplier) MyServiceFactory
			.getInstance(MyServiceFactory.SEARCH_GOODS_FROM_TEXT_AND_SUPPLIER);
	private GoodsFromSupplierService goodsFromSupplierService = (GoodsFromSupplierService) MyServiceFactory
			.getInstance(MyServiceFactory.GOODS_FROM_SUPPLIER);

	private int width;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels; // 屏幕宽度（像素）

		setup();
		normalDataLoader.load();
	}


	private void setup() {
		setContentView(R.layout.sup_goods_manager_list);

		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);
		ivAddGoodsButton = (ImageView) findViewById(R.id.ivPublicTitleOther);

		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);

		etGoodsManagerSearch = (EditText) findViewById(R.id.etPublicSearchText);
		// 设置图片的高度为图片的宽度
		LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) etGoodsManagerSearch
				.getLayoutParams();
		params.width = width - DisplayUtil.dip2px(this, 78);
		etGoodsManagerSearch.setLayoutParams(params);

		lvGoodsManagerList = (ListView) findViewById(R.id.lvGoodsManagerList);

		adater = new SupGoodsListAdapter(this, cloths);
		myListBottom = new MyListBottom(getBaseContext(), lvGoodsManagerList);

		normalDataLoader.setOnloadDataListener(this);

		tvTitle.setText("商品管理");
		ivAddGoodsButton.setImageResource(R.drawable.button_yellow_add);

		ivReturnButton.setOnClickListener(myClickListener);
		ivAddGoodsButton.setOnClickListener(myClickListener);
		etGoodsManagerSearch.addTextChangedListener(myTextWatcher);

		lvGoodsManagerList.setAdapter(adater);
		adater.notifyDataSetChanged();

		lvGoodsManagerList.setOnScrollListener(myScrollListener);
		lvGoodsManagerList.setOnItemClickListener(myItemClickListener);
		lvGoodsManagerList.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				EnvironmentUtil.closeInputMethod(SupGoodsManagerActivity.this);
				return false;
			}
		});

	}

	/**
	 * 输入框编辑监听
	 */
	TextWatcher myTextWatcher = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
		}

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			cloths.clear();
			startIndex = 0;
			isReachLast = false;
			if (!normalDataLoader.getLoading()) {
				normalDataLoader.load();
			}
		}
	};

	/**
	 * 滚动监听
	 */
	OnScrollListener myScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_FLING:
				adater.setBusy(true);
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				adater.setBusy(false);
				break;
			case OnScrollListener.SCROLL_STATE_IDLE:
				int lastIndex = adater.getCount();
				adater.setBusy(false);
				if (visibleLastIndex == lastIndex && !isReachLast) {
					normalDataLoader.load();
				}
				break;
			default:
				break;
			}
			adater.notifyDataSetChanged();
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			visibleLastIndex = firstVisibleItem + visibleItemCount - 1;

		}
	};

	/**
	 * 系统按键的设置
	 * *****************************************************************************************************************************************/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent(getBaseContext(), SupIndexActivity2.class);
			startActivity(intent);
			this.finish();
			return false;
		}
		return false;
	}

	/**
	 * 选项点击监听
	 */
	OnItemClickListener myItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if ((adater.getCount() != position)) {
				Intent intent = new Intent(SupGoodsManagerActivity.this,
						SupGoodsDetailsActivity.class);
				SupCache.cloth = cloths.get(position);
				startActivity(intent);
				SupGoodsManagerActivity.this.finish();
			}
		}

	};

	/**
	 * 页面其他按钮的点击监听
	 */
	OnClickListener myClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = null;
			switch (v.getId()) {

			case R.id.ivPublicTitleReturn:
				adater.clearCache();
				intent = new Intent(getBaseContext(), SupIndexActivity2.class);
				startActivity(intent);
				SupGoodsManagerActivity.this.finish();
				break;

			case R.id.ivPublicTitleOther:
				SupInputGoodsInfoActivity.TO_ADD_GOODS = true;
				SupCache.from = 1;
				if (SupCache.pictureList != null
						&& SupCache.pictureList.size() > 0) {
					SupCache.pictureList.clear();
				}
				intent = new Intent(SupGoodsManagerActivity.this,
						SupCameraActivity.class);
				startActivity(intent);
				SupGoodsManagerActivity.this.finish();
				break;

			default:
				break;
			}

		}
	};

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub
		myListBottom.showProgressBar();
		myListBottom.setText("加载中～");
	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		GsonBean gsonBean = null;
		if (strSearchText.equals("") || strSearchText == null) {
			gsonBean = goodsFromSupplierService.execute(startIndex, length,
					keyCache.supId);
		} else {
			strSearchText = etGoodsManagerSearch.getText().toString();
			gsonBean = searchGoodsFormTextAndSupplier.execute(startIndex,
					length, strSearchText, keyCache.supId);
		}
		if (CheckStateUtil.check(gsonBean)) {
			List<Cloth> clothList = DataUtil.gson.fromJson(
					gsonBean.getStrJson(), new TypeToken<List<Cloth>>() {
					}.getType());
			startIndex += clothList.size();
			cloths.addAll(clothList);
			msg.what = MyStateUtil.LIST_CHANGE;
		} else {
			// 查找不到数据的情况
			isReachLast = true;
			msg.what = MyStateUtil.LIST_IS_REACH_LAST;
		}
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		myListBottom.hideProgressBar();
		switch (state) {
		case MyStateUtil.LIST_CHANGE:
			Log.i("listChange",
					"------------------listChange--------------------");
			myListBottom.setText("向上拉加载数据");
			break;
		case MyStateUtil.LIST_IS_REACH_LAST:
			myListBottom.setText("没有相应数据咯～");
			break;
		case MyStateUtil.NOT_NET_CONNECTION:
			myListBottom.setText("无网络连接～");
			break;
		case MyStateUtil.ERROR_NET_CONNECTION:
			myListBottom.setText("向上拉加载数据");
			ToastUtil.show(SupGoodsManagerActivity.this, "网络连接异常");
			break;
		default:
			break;
		}
		adater.notifyDataSetChanged();
	}

}
